<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * HITI AdminCP
 *
 * @package     HITI AdminCP Project
 * @since       Monday, October 21, 2013, 6:00 PM
 * @final       
 * @category    Models
 * @see 		Modules
 * @author      PHUOCNGUYEN - HITI Dev Team
 * @copyright   Copyright (c) 2013, HITI Corp
 */

class Modules_model extends CI_Model {
	public function __construct()
	{
		parent::__construct();
	}

	public function show($cat, $uri)
	{
		$this->db->query("SET NAMES 'LATIN1'");
		$this->db->where('deleted', $uri['deleted']);
		$this->db->where('nhom', $cat);
		$this->db->order_by('sort_order DESC');
		if ($uri['q'] != '')
		{
			$this->db->where(sprintf('(`name_vn` LIKE "%%%s%%" OR `file` LIKE "%%%s%%")', $uri['q'], $uri['q']));
		}
		$last_login = $GLOBALS['user']['last_login'];
		$this->db->select('*, IF ('.sprintf('date_added >= %1$s', $this->db->escape($last_login)).', 1, 0) as isnew', false);
		$query = $this->db->get('modules');
		if ($query->num_rows() > 0)
		{
			return $query->result_array();
		}
		else
		{
			return false;
		}
	}

	public function info($id)
	{
		$this->db->query("SET NAMES 'LATIN1'");
		$this->db->where('id', $id);
		$query = $this->db->get('modules');
		if ($query->num_rows() > 0)
		{
			return $query->row_array();
		}
		else
		{
			$fields = $this->db->field_data('modules');
			$default_data = array();
			foreach ($fields as $field)
			{
				$default_data[$field->name] = $field->default;
			}
			return $default_data;
		}
	}

	public function process($data, $id = '')
	{
		if(!is_array($data))
		{
			return false;
		}
		$this->db->query("SET NAMES 'LATIN1'");
		if ($id > 0)
		{
			unset($data['date_added']);
			$this->db->where('id', $id);
			$this->db->update('modules', $data);
			write_log('update_modules', $data['name_vn']);
		}
		else
		{
			$this->db->insert('modules', $data);
			write_log('add_modules', $data['name_vn']);
		}
		$old_code = '';
		if ($id > 0) $old_code = get_data('modules', 'id = '.$id, 'file');
		if ($old_code != $data['file'])
		{
			$this->db->query("UPDATE users SET user_rights = REPLACE(user_rights, '".$old_code."', '".$data['file']."')");
		}		
		return true;
	}

	public function update_admin_rights($data)
	{
		$this->db->where('id', 1);
		$this->db->update('users', $data);
		return true;
	}
}

/* End of file modules_model.php */
/* Location: ./application/models/modules_model-.php */